﻿Imports System.IO
Imports iTextSharp.text.html.simpleparser

Public Class InformeController
    Inherits BaseController

    Private ReadOnly repoDirección_ As DirecciónRepository
    Private ReadOnly repoAviso_ As AvisoRepository
    Private ReadOnly repoPediatraAsindo_ As PediatraAsindoRepository

    Public Sub New(ByVal repoPediatraAsindo As PediatraAsindoRepository, ByVal saver As ContextSaver,
        ByVal repoAviso As AvisoRepository,
        ByVal repoDirección As DirecciónRepository)

        MyBase.New(repoPediatraAsindo, saver)
        repoDirección_ = repoDirección
        repoAviso_ = repoAviso
        repoPediatraAsindo_ = repoPediatraAsindo
    End Sub

    Private Function PDF(Of T)(ByVal partialViewName As String) As ActionResult
        Return PDF(Of T)(partialViewName, Nothing)
    End Function

    Private Function PDF(Of T)(ByVal partialViewName As String, ByVal model As T) As ActionResult
        Dim context = Me.ControllerContext

        Dim buf As Byte() = Nothing
        Dim pdfTemp As New MemoryStream()
        Dim result = ViewEngines.Engines.FindPartialView(context, partialViewName)

        If result.View IsNot Nothing Then
            Dim htmlTextView As String = GetViewToString(context, New ViewDataDictionary(Of T) With {.Model = model}, result)
            Dim doc As New iTextSharp.text.Document()
            Dim writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, pdfTemp)
            writer.CloseStream = False
            doc.Open()

            AddHTMLText(doc, htmlTextView)
            doc.Close()

            buf = New Byte(CInt(pdfTemp.Position - 1)) {}
            pdfTemp.Position = 0
            pdfTemp.Read(buf, 0, buf.Length)
        End If
        Return File(buf, "application/pdf", "Etiquetas.pdf")
    End Function

    Private Shared Sub AddHTMLText(ByVal doc As iTextSharp.text.Document, ByVal html As String)
        Dim st As New StyleSheet

        st.LoadStyle("wrapper", "font-family", "Tahoma")
        st.LoadStyle("wrapper", "font-size", "9pt")
        st.LoadStyle("wrapper", "margin", "0")
        st.LoadStyle("etiqueta", "border", "1mm solid black")
        st.LoadStyle("etiqueta", "padding", "4mm")
        st.LoadStyle("etiqueta", "width", "103mm")
        st.LoadStyle("etiqueta", "height", "22.75mm")
        st.LoadStyle("etiqueta", "float", "left")
        st.LoadStyle("page_break", "page-break-after", "always")

        Dim htmlarraylist As List(Of iTextSharp.text.IElement) = HTMLWorker.ParseToList(New StringReader(html), st)

        For Each item In htmlarraylist
            doc.Add(item)
        Next
    End Sub

    Private Shared Function GetViewToString(ByVal context As ControllerContext, ByVal viewData As ViewDataDictionary, ByVal result As ViewEngineResult) As String
        Dim viewResult As String = ""
        Dim tempData As New TempDataDictionary()
        Dim sb As New StringBuilder()
        Using sw As New StringWriter(sb)

            Using output As New HtmlTextWriter(sw)

                Dim viewContext As New ViewContext(context, result.View, viewData, tempData, output)

                result.View.Render(viewContext, output)
            End Using

            viewResult = sb.ToString()
        End Using
        Return viewResult
    End Function

    Function Etiquetas() As ActionResult
        Return View("Etiquetas", repoDirección_.All.Include("Personas").Include("TipoVía").Include("Población"))
        'Return PDF("Etiquetas2", repoDirección_.All.Include("Personas").Include("TipoVía").Include("Población"))
    End Function

    Function Honorarios() As ActionResult
        ViewData("ListaPediatrasAsindo") = repoPediatraAsindo_.Desplegable
        Return View(VistaFormulario)
    End Function

    <HttpPost()>
    Function Honorarios(ByVal fechaInicio As Date, ByVal fechaFin As Date, ByVal pediatras() As Integer) As ActionResult
        If fechaInicio >= fechaFin Then
            ModelState.AddModelError("", "El intervalo de fechas no es válido")
        End If
        If pediatras Is Nothing Then
            ModelState.AddModelError("", "Debe escoger al menos un pediatra")
        End If

        If ModelState.IsValid Then
            Dim fechaLímite = fechaFin.AddDays(1)
            Dim query As IQueryable(Of Aviso) = repoAviso_.All
            query = query.Where(Function(aviso) aviso.FechaHora >= fechaInicio)
            query = query.Where(Function(aviso) aviso.FechaHora < fechaLímite)
            If pediatras Is Nothing Then
                query = query.Where(Function(aviso) False)
            Else
                query = query.Where(Function(aviso) pediatras.Contains(aviso.PediatraAsindoId))
            End If
            query = query.Include("Paciente").Include("Dirección.Población").Include("Dirección.TipoVía").Include("PediatraAsindo")

            Dim query2 = repoPediatraAsindo_.All().Where(Function(ped) pediatras.Contains(ped.Id))

            ViewData("Pediatras") = Join(query2.ToList.Select(Function(ped) ped.NombreCompletoDerecho).ToArray, ", ")
            ViewData("FechaInicio") = fechaInicio
            ViewData("FechaFin") = fechaFin
            Return View("Honorarios", query)
        Else
            Return Honorarios()
        End If
    End Function

    Protected Overrides Sub CargarDatosComunes()
    End Sub

    Protected Overrides Function VistaFormulario() As String
        Return "FormHonorarios"
    End Function

    Protected Overrides Function VistaLista() As String
        Return ""
    End Function
End Class
